java模仿http表单提交数据、模仿http表单上传文件示例
package com.snca.cloudsign.main;import java.io.File;import java.io.IOException;import java.nio.charset.Charset;import org.apache.http.Consts;import org.apache.http.HttpEntity;import org.apache.http.ParseException;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ContentType;import org.apache.http.entity.StringEntity;import org.apache.http.entity.mime.MultipartEntityBuilder;import org.apache.http.entity.mime.content.FileBody;import org.apache.http.entity.mime.content.StringBody;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.util.EntityUtils;public class CloudSignRestUtil { /** * 正常数据请求 * @param url * @param data * @return */ public static String commDataRequest(String url,String data)throws ClientProtocolException,ParseException,IOException{ HttpPost httpPost = new HttpPost(url); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; httpClient = HttpClients.createDefault(); HttpEntity entity = new StringEntity(data,Consts.UTF_8); httpPost.setEntity(entity); httpPost.addHeader("Content-Type", "application/json"); httpPost.setEntity(entity); try { response = httpClient.execute(httpPost); return EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8")); }finally { if(response != null){ response.close(); } if(httpClient != null){ httpClient.close(); } } } /** * 带文件的数据接口请求 * @param url * @param data * @return */ public static String fileDataRequest(String url,String data,File pdfFile)throws ClientProtocolException,ParseException,IOException{ CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try{ httpClient = HttpClients.createDefault(); StringBody requestData = new StringBody(data, ContentType.create( "text/plain", Consts.UTF_8)); FileBody bin = new FileBody(pdfFile); HttpEntity entity = MultipartEntityBuilder.create() .addPart("pdfFile", bin) .addPart("requestData", requestData) .build(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(entity); // 发起请求 并返回请求的响应 response = httpClient.execute(httpPost); // 获取响应对象 HttpEntity resEntity = response.getEntity(); String responseStr = EntityUtils.toString(response.getEntity(),Charset.forName("UTF-8")); // 销毁 EntityUtils.consume(resEntity); return responseStr; }finally { if(response != null){ response.close(); } if(httpClient != null){ httpClient.close(); } } } }
评论